package it.univaq.mancoosi.injectors.systemconfiguration.managers;

import it.univaq.mancoosi.injectors.systemconfiguration.managers.ubuntu.UbuntuEnvironmentManager;
import it.univaq.mancoosi.mancoosimm.BootScript;
import it.univaq.mancoosi.mancoosimm.MancoosiFactory;
import it.univaq.mancoosi.mancoosimm.Module;
import it.univaq.mancoosi.mancoosimm.ModuleCache;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;

public abstract class ModuleCacheManager {
	protected static  ModuleCacheManager INSTANCE ;	 
	protected MancoosiFactory factory; 
	private ModuleCache moduleCache;
	protected HashMap<String, ModuleCache> moduleCacheMap;
	protected HashMap<String, Module> moduleMap;

	// Private constructor prevents instantiation from other classes
	protected ModuleCacheManager() {
		factory = MancoosiFactory.eINSTANCE; 
		moduleCache = factory.createModuleCache();
		this.moduleCacheMap = new HashMap<String, ModuleCache>();
		this.moduleMap = new HashMap<String, Module>();
	}

	public static ModuleCacheManager getInstance() {
		return INSTANCE;
	}

	public abstract void createModuleCachesFromSystem();

	public abstract void synchronize() throws IOException;	
	
	public abstract Boolean existsModule(String moduleName, String moduleCacheVersion);
	
	public abstract Boolean existsModuleCache(String moduleCacheVersion);
	 
	public void syncMap () {
		Iterator<ModuleCache> cacheIterator  = null;
		Iterator<Module> moduleIterator  = null;
		if(UbuntuEnvironmentManager.getInstance().getEnvironment().getModuleCache() != null){
			cacheIterator = UbuntuEnvironmentManager.getInstance().getEnvironment().getModuleCache().iterator();
		}
		if(cacheIterator != null){
			while (cacheIterator.hasNext()) {
				int indexMc = UbuntuEnvironmentManager.getInstance().getEnvironment().getModuleCache().indexOf(cacheIterator.next());
				ModuleCache mc = UbuntuEnvironmentManager.getInstance().getEnvironment().getModuleCache().get(indexMc);
				this.moduleCacheMap.put(mc.getVersion(), mc);
				moduleIterator = mc.getModules().iterator();
				while (moduleIterator.hasNext()) {
					Module curr = moduleIterator.next();
					String moduleIdentifier = curr.getName() +"+"+ mc.getVersion();
					this.moduleMap.put(moduleIdentifier, curr);
				}
			}
		}
	} 

}
